package com.mrzhou.web.interceptor;

import com.mrzhou.core.tool.constants.CloudConstant;
import com.mrzhou.core.tool.constants.TokenConstant;
import com.mrzhou.core.tool.utils.Func;
import com.mrzhou.core.tool.utils.JacksonUtil;
import com.mrzhou.core.tool.utils.StringUtil;
import com.mrzhou.web.props.CloudWebProperties;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

/**
 * @author qiang.zhou
 * feign 拦截器
 */
@Slf4j
public class FeignRequestHeaderInterceptor implements RequestInterceptor {

    /** Cloud-Auth 和 Cloud-Id 两个header会自动传递； 如果有的话 */
    private final String DEFAULT_HEADERS = TokenConstant.TOKEN_HEADER_NAME + "," + CloudConstant.HEADER_CLOUD_ID;

    private final CloudWebProperties props;

    public FeignRequestHeaderInterceptor(CloudWebProperties props) {
        this.props = props;
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null == attributes) {
            return;
        }

        HttpServletRequest request = attributes.getRequest();
        // 处理默认传递的header
        List<String> list = Func.toArray(DEFAULT_HEADERS);
        // 处理配置文件中加入的header
        if(StringUtil.isNotBlank(props.getHeaders())) {
            list.addAll(Func.toArray(props.getHeaders()));
        }

        // 向Feign中添加请求头
        Optional.ofNullable(request).ifPresent(req -> list.stream().forEach(name -> requestTemplate.header(name, req.getHeader(name))));
        log.info("Feign添加的Header头信息： {}", Func.join(list));
    }

}
